package com.we823.cms.controller.manage.sys;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.github.pagehelper.PageInfo;
import com.we823.cms.common.web.pageable.PageRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.we823.cms.common.WebConstants;
import com.we823.cms.common.utils.RequestUtil;
import com.we823.cms.controller.manage.AbstractManageController;
import com.we823.cms.model.sys.Role;
import com.we823.cms.model.sys.User;
import com.we823.cms.repository.service.sys.RoleService;
import com.we823.cms.repository.service.sys.UserService;

@Controller
@RequestMapping(WebConstants.MANAGE_URL+"/user")
public class UserManageController extends AbstractManageController<User, Integer> {

	private String baseUrl = WebConstants.MANAGE_URL+"/user/";
	
	@Autowired
	private RoleService roleService;
	
	private UserService userService;
	
	@Autowired
	public UserManageController(UserService userService) {
		super(userService);
		super.baseUrl = baseUrl;
		super.entityName="user";
		
		this.userService=userService;
	}

	@Override
	public PageInfo<User> getData(PageRequest pageRequest,
								  HttpServletRequest request, Model model, boolean pageable) {
		PageInfo<User> userPage;
		
		if (pageable) {
			userPage = userService.findAll(pageRequest);
		}else {
			userPage = new PageInfo<>(userService.findAll(getSort(request)));
		}
		return userPage;
	}

	@Override
	public String preAdd(Model model) {
		java.util.List<Role> roles = roleService.findAll();
		model.addAttribute("roles",roles);
		return super.preAdd(model);
	}
	
	@Override
	public String add(@ModelAttribute("user") User entity, BindingResult result) {
		if (entity!=null) {
			String passwordString = entity.getPassword();
			passwordString = new Md5Hash(passwordString,entity.getSalt()).toString();
			entity.setPassword(passwordString);
		}
		return super.add(entity, result);
	}
	
	@Override
	public String preEdit(@RequestParam("id")Integer key, Model model) {
		java.util.List<Role> roles = roleService.findAll();
		model.addAttribute("roles",roles);
		
		return super.preEdit(key, model);
	}

	@RequestMapping("editEx")
	public String edit(HttpServletRequest request,User entity,BindingResult result) {
		if (entity!=null) {
			User oldUserModel = userService.findOne(entity.getId());
			String passwd = RequestUtil.getValueByName(request, "password");
			String newPasswd = RequestUtil.getValueByName(request, "newpassword");
			if (StringUtils.isEmpty(passwd)) {
				entity.setPassword(oldUserModel.getPassword());
			}else {
				passwd = new Md5Hash(passwd, entity.getSalt()).toString();
				if (!oldUserModel.getPassword().equals(passwd)) {
					result.rejectValue("password", "00001", "原始密码错误，无法修改密码");
					return baseUrl+"preEdit";
				}else {
					entity.setPassword(new Md5Hash(newPasswd, entity.getSalt()).toString());
				}
			}
		}
		return super.edit(entity, result);
	}
	
	@RequestMapping("change")
	public String change(HttpServletRequest request,Model model) {
		String action = RequestUtil.getValueByName(request, "action");
		if("save".equals(action)) {
			int id = RequestUtil.getValueByName(request, "id", 0);
			if (id>0) {
				User oldUserModel = userService.findOne(id);
				if (oldUserModel!=null) {
					String passwordString = RequestUtil.getValueByName(request, "password");
					if (!StringUtils.isEmpty(passwordString)) {
						passwordString = new Md5Hash(passwordString, oldUserModel.getSalt()).toString().toLowerCase();
						if (passwordString.equals(oldUserModel.getPassword().toLowerCase())) {
							String newpassword = RequestUtil.getValueByName(request, "newpassword");
							newpassword = new Md5Hash(newpassword,oldUserModel.getSalt()).toString();
							oldUserModel.setPassword(newpassword);
							userService.edit(oldUserModel, id);
							model.addAttribute("user",oldUserModel);
							model.addAttribute("hasError",false);
							model.addAttribute("msg","密码修改成功");
						}else {
							model.addAttribute("hasError",true);
							model.addAttribute("msg","原密码错误，无法修改密码！");
							model.addAttribute("user",oldUserModel);
						}
					}
				}
			}
		}else {
			Subject subject = SecurityUtils.getSubject();
			User userModel = (User) subject.getSession().getAttribute(WebConstants.CURRENT_USER);
			
			model.addAttribute("user",userModel);
			model.addAttribute("hasError",false);
		}
		
		return baseUrl+"change";
	}

	@RequestMapping("info")
	public String info(HttpServletRequest request,Model model) {
		String action = RequestUtil.getValueByName(request, "action");
		Subject subject = SecurityUtils.getSubject();
		User userModel = (User) subject.getSession().getAttribute(WebConstants.CURRENT_USER);
		if ("save".equals(action)) {
			int id = RequestUtil.getValueByName(request, "id", 0);
			if (id>0) {
				String emailString = RequestUtil.getValueByName(request, "email");
				String mobilePhone = RequestUtil.getValueByName(request, "mobilePhone");
				userModel.setEmail(emailString);
				userModel.setMobilePhone(mobilePhone);
				userModel.setEdittime(new Date());
				userService.edit(userModel, id);
				
				userModel = userService.findOne(id);
				model.addAttribute("msg","修改成功");
			}
			
		}
		model.addAttribute("user",userModel);
		return baseUrl +"info";
	}
	
	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	@Override
	public void setIndetity() {
		setResourceIdentity("sys:user");
	}
	
	
}
